package com.bizmerce.rnd.oms.cmmn;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ThisApplicationContext {

	private static Object lock = new Object();
	
	private static ThisApplicationContext applicationContext;

	private ServletContext servletContext;

	private void init(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	private ServletContext getServletContext() {
		return servletContext;
	}

	public static Object getBean(String name) {
		ApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getApplicationContext()
						.getServletContext());
		return context.getBean(name);
	}

	public static Object getBean(String name, Class requiredType) {
		ApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getApplicationContext()
						.getServletContext());
		return context.getBean(name, requiredType);
	}

	public static void initApplicationContext(ServletContext servletContext) {
		synchronized (lock) {
			if (applicationContext == null) {
				applicationContext = new ThisApplicationContext();
				applicationContext.init(servletContext);
			}
		}
	}

	private static ThisApplicationContext getApplicationContext() {
		if (applicationContext == null) {
			throw new RuntimeException(
					"initApplicationContext(ServletContext)를 먼저 호출하여 초기화하여야 합니다.");
		}
		return applicationContext;
	}
}
